package me.ljd.yigo.utils;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.PropertyResourceBundle;

import com.bokesoft.yes.mid.util.PropertyUtil;
import com.bokesoft.yigo.meta.dataobject.MetaTable;
import com.bokesoft.yigo.meta.form.MetaForm;
import com.bokesoft.yigo.mid.base.DefaultContext;
import com.bokesoft.yigo.mid.connection.IDBManager;
import com.bokesoft.yigo.mid.util.DBManagerUtil;
import com.bokesoft.yigo.struct.datatable.DataTable;
import com.bokesoft.yigo.tools.document.DataTableUtil;

public class DBManagerUtil2 {
	private static String[] dsnArr = null;
	private static Map<Object,IDBManager> dsnMap = new HashMap<>();
	
	public static void init() {
		System.out.println("DBManagerUtil2.init()");
		if(dsnArr != null) {return;}//防止多次初始化
		try {
			PropertyResourceBundle coreBundle = getCoreBundle();
			if (coreBundle.containsKey("DSN")) {
				String dsns = coreBundle.getString("DSN");
				dsnArr = dsns.split(",");
			}
		} catch (Throwable e) {
			System.out.println("读取DSN配置出错！");
			e.printStackTrace();
		}
	}
	
	public static void init(DefaultContext content) throws Throwable{
		setDBManager(content.getDBManager());
	}

	public static IDBManager getDBManager(String dsn) throws Throwable{
		IDBManager dbManager=null;
		if(dsnMap.get(dsn)==null) {
			dbManager = DBManagerUtil.getDBManager(dsn);
			dsnMap.put(dsn, dbManager);
		}
		dbManager = dsnMap.get(dsn);
		return dbManager;
	}
	public static IDBManager getDBManager(int index) throws Throwable{
		String dsn = dsnArr[index];
		return getDBManager(dsn);
	}
	protected static PropertyResourceBundle getCoreBundle() throws Throwable{
		FileInputStream coreIs = PropertyUtil.readProperties("core.properties");
		PropertyResourceBundle coreBundle = new PropertyResourceBundle(coreIs);
		return coreBundle;
	}
	public static void dsnMapClear() {
		dsnMap.clear();
	}
	public static void setDBManager(IDBManager dbm) {
		String dsn = dbm.getKey();
		if(dsnMap.get(dsn)==null) {
			dsnMap.put(dsn, dbm);
		}
	}
	public static DataTable getTableNew(DefaultContext context) throws Throwable{
//		tableNew = new DataTable();//手动构建对于普通查询是可以的，但是对于列拓展不行，采用下面的方式
//		tableNew.addColumn(new ColumnInfo("Row_Key", DataType.LONG));
//		tableNew.addColumn(new ColumnInfo("Col_Name", DataType.STRING));
//		tableNew.addColumn(new ColumnInfo("Col_Value", DataType.STRING));
//		ColumnInfo keyColInfo = new ColumnInfo(SystemField.OID_SYS_KEY, DataType.LONG);
//		keyColInfo.setPrimary(true);
//		tableNew.addColumn(keyColInfo);
		//Document doc = context.getDocument();
//		tableNew = doc.get(0);//这样获取不到，不知道具体原因
        MetaForm metaForm = context.getVE().getMetaFactory().getMetaForm(context.getFormKey());
        MetaTable metaTable = metaForm.getDataSource().getDataObject().getTableCollection().get(0);
		return DataTableUtil.newEmptyDataTable(metaTable);	
	}	
}
